<template>
  <el-card shadow="hover" class="mt-20">
    <el-form @submit.prevent>
      属性名
      <el-input
        placeholder="请输入属性名"
        class="attrList__inp"
        v-model="attrFormData.attrName" />
    </el-form>

    <div class="mt-20">
      <el-button
        type="primary"
        :icon="CirclePlusFilled"
        :disabled="!attrFormData.attrName"
        @click="addAttrValue">
        添加属性值
      </el-button>
    </div>

    <el-table :data="attrFormData.attrValueList" class="mt-20">
      <el-table-column label="序号" width="80" type="index" />
      <el-table-column label="属性值名称">
        <template v-slot="{ row, $index }">
          <el-input
            v-if="row.isShowEdit"
            v-model.trim="row.valueName"
            size="small"
            ref="inpRef"
            @blur="switchShow(row, $index)"
            @keyup.enter="switchShow(row, $index)" />

          <div v-else @click="switchEdit(row)">
            {{ row.valueName }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template v-slot="{ row, $index }">
          <el-popconfirm
            :title="`确认删除 ${row.valueName} 吗?`"
            @confirm="delAttrValue($index)"
            width="200">
            <template #reference>
              <el-button type="danger" :icon="Delete" size="small"></el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <div class="mt-20">
      <el-button type="primary" :disabled="disabled" @click="submit">
        保存
      </el-button>
      <el-button @click="cancel">取消</el-button>
    </div>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "AddOrUpdateAttr",
};
</script>

<script lang="ts" setup>
import { ref, reactive, nextTick, computed } from "vue";
import type {
  AttrValueList,
  AttrValueItem,
  AttrItem,
} from "@/api/product/model/attrModels";
import { addAttrInfoApi } from "@/api/product/attr";

import { useCategoryStore } from "@/stores/category";
import { useAttrStore } from "@/stores/attr";

import { CirclePlusFilled, Delete } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";

/************************提交属性值*****************************/
const categoryStore = useCategoryStore();
const attrStore = useAttrStore();
// 提交数据
const submit = async () => {
  // 发送添加属性请求
  const data: AttrItem = {
    ...attrFormData,
    categoryId: categoryStore.category3Id,
    categoryLevel: 3,
  };

  // 修改和添加用的同一个api  使用id区分
  const id = attrStore.attr.id;
  if (id) {
    data.id = id;
  }

  await addAttrInfoApi(data);

  ElMessage.success(`${id ? "修改" : "添加"}属性成功`);
  cancel();
};

/**************************初始化数据********************************* */
// 定义数据

const attrFormData = reactive<AttrItem>({
  attrName: attrStore.attr.attrName,
  attrValueList: attrStore.attr.attrValueList,
});

/**************************计算属性保存按钮********************************* */

// 计算保存按钮是否禁用
const disabled = computed(() => {
  return (
    !attrFormData.attrName ||
    !attrFormData.attrValueList.some((attrValue) => attrValue.valueName)
  );
});

/************************删除模态框*****************************/

// 删除框
const delAttrValue = (index: number) => {
  attrFormData.attrValueList.splice(index, 1);
  ElMessage.success("删除成功~~~");
};

/************************添加属性值*****************************/

// 添加属性值
const addAttrValue = () => {
  attrFormData.attrValueList.push({
    isShowEdit: true,
    valueName: "",
  });
  // 页面更新完获取input焦点
  nextTick(() => {
    inpRef.value.focus();
  });
};

/***************************input获得焦点*******************************/
// 获取input实例
const inpRef = ref();
// 失去焦点 展示显示内容
const switchShow = (row: AttrValueItem, index: number) => {
  // 如果没有输入内容 就删除当前行
  if (!row.valueName) {
    attrFormData.attrValueList.splice(index, 1);
    return;
  }

  // 查找是否有重复的值
  const isRepeat = attrFormData.attrValueList.some((attrValue) => {
    // 自己不需要和自己比
    if (attrValue === row) return false;
    if (attrValue.valueName === row.valueName) return true;
    return false;
  });

  // 有重复值就提示
  if (isRepeat) {
    ElMessage.warning("不能输入重复的属性值值");
    attrFormData.attrValueList.splice(index, 1);
    return;
  }

  // 切换到显示内容
  row.isShowEdit = false;
};

// 展示编辑内容
const switchEdit = async (row: AttrValueItem) => {
  row.isShowEdit = true;

  await nextTick();
  inpRef.value.focus();
};

/**************************接收自定义事件**************************** */
// 接收自定义事件
const emit = defineEmits(["setIsShowAttr"]);
const cancel = () => {
  // 组件切换标识
  emit("setIsShowAttr", true);
};
</script>

<style scoped>
.attrList__inp {
  width: 200px;
  margin-left: 20px;
}
</style>
